package cn.iocoder.yudao.module.cook.service.caidan;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.cook.controller.admin.caidan.vo.*;
import cn.iocoder.yudao.module.cook.dal.dataobject.caidan.CaidanDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.cook.dal.mysql.caidan.CaidanMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cook.enums.ErrorCodeConstants.*;

/**
 * 食谱菜单 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CaidanServiceImpl implements CaidanService {

    @Resource
    private CaidanMapper caidanMapper;

    @Override
    public Long createCaidan(CaidanSaveReqVO createReqVO) {
        // 插入
        CaidanDO caidan = BeanUtils.toBean(createReqVO, CaidanDO.class);
        caidanMapper.insert(caidan);
        // 返回
        return caidan.getId();
    }

    @Override
    public void updateCaidan(CaidanSaveReqVO updateReqVO) {
        // 校验存在
        validateCaidanExists(updateReqVO.getId());
        // 更新
        CaidanDO updateObj = BeanUtils.toBean(updateReqVO, CaidanDO.class);
        caidanMapper.updateById(updateObj);
    }

    @Override
    public void deleteCaidan(Long id) {
        // 校验存在
        validateCaidanExists(id);
        // 删除
        caidanMapper.deleteById(id);
    }

    private void validateCaidanExists(Long id) {
        if (caidanMapper.selectById(id) == null) {
            throw exception(CAIDAN_NOT_EXISTS);
        }
    }

    @Override
    public CaidanDO getCaidan(Long id) {
        return caidanMapper.selectById(id);
    }

    @Override
    public PageResult<CaidanDO> getCaidanPage(CaidanPageReqVO pageReqVO) {
        return caidanMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CaidanDO> getCaidanList(CaidanListReqVO listReqVO) {
        List<CaidanDO> list = caidanMapper.selectList(listReqVO);
        list.sort(Comparator.comparing(CaidanDO::getSort));
        return list;
    }
}